package com.hlbspringcloud.mq;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @Author huanglibin
 * @Project mq
 * @Description 消费者2，接受routing-key为log.*的消息
 * @Date 2020-12-04-15-28-09
 * @Version 1.0
 */
public class TopicsReceiver2 {
    /**
     * 路由名称
     */
    public static final String ROUTING_NAME="topics mode";
    /**
     * 队列名称
     */
    public static final String ROUTING_QUEUE="topics queue2";

    public static void receiveMessage() throws Exception{
        //创建连接
        Connection rabbitmqConnection = RabbitmqUntil.getRabbitmqConnection();
        //获取通道
        final Channel channel = rabbitmqConnection.createChannel();
        //申明队列
        channel.queueDeclare(ROUTING_QUEUE,true,false,false,null);
        //申明每次处理一条数据
        channel.basicQos(1);
        //绑定路由(并且指定routing-key为error、warning)
        channel.queueBind(ROUTING_QUEUE,ROUTING_NAME,"log.*");

        DefaultConsumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                try{
                    System.out.println("主题模式消费者2："+new String(body,"utf-8"));
                }catch (Exception e){
                    e.printStackTrace();
                }finally {
                    channel.basicAck(envelope.getDeliveryTag(),false);
                }
            }
        };

        channel.basicConsume(ROUTING_QUEUE,false,consumer);
    }

    public static void main(String[] args) throws Exception{
        TopicsReceiver2.receiveMessage();
    }
}
